package com.weiter.common.core.utils.ip;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.weiter.common.core.config.WeiterConfig;
import com.weiter.common.core.constant.Constants;
import com.weiter.common.core.utils.StringUtils;
import com.weiter.common.core.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取地址类
 * @author weiter
 */
public class AddressUtils {

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "未知";

    /**
     * 获取IP地理位置
     * @param ip IP
     * @return 地理位置信息
     */
    public static String getRealAddressByIP(String ip) {
        String realAddressByNotNetwork = getRealAddressByNotNetwork(ip);
        if (!UNKNOWN.equals(realAddressByNotNetwork)) {
            return realAddressByNotNetwork;
        }
        return getRealAddressByNetwork(ip);
    }

    /**
     * 在线获取IP地理位置
     * @param ip IP
     * @return 地理位置信息
     */
    public static String getRealAddressByNetwork(String ip) {
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (WeiterConfig.isAddressEnabled()) {
            try {
                log.info("在线获取IP:{}地理位置", ip);
                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
                if (StringUtils.isEmpty(rspStr)) {
                    log.error("在线获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("在线获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }

    /**
     * 离线获取IP地理位置
     * @param ip IP
     * @return 地理位置信息
     */
    public static String getRealAddressByNotNetwork(String ip) {
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (WeiterConfig.isAddressEnabled()) {
            try {
                log.info("离线获取IP:{}地理位置", ip);
                String rspStr = RegionUtil.getCityInfo(ip);
                if (StringUtils.isEmpty(rspStr)) {
                    log.error("离线获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                String[] obj = rspStr.split("\\|");
                String region = obj[2];
                String city = obj[3];
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("离线获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }
}
